import { type AxiosPromise } from "axios";
import { get, post } from "@/utils/request";
import { Admin } from "@/features/admins/data/schema";
import { useMutation, useQueryClient } from "@tanstack/react-query";

export const adminKeys = {
  all: () => ["admins"],
};

export const admins = (): AxiosPromise => {
  return get("/admins", {});
};

export interface AdminDeleteData {
  [key: string]: unknown;
}

export const adminDelete = (data: AdminDeleteData): AxiosPromise => {
  return post("/admins/delete", data);
};

export interface AdminAddData {
  [key: string]: unknown;
}

export const adminAdd = (data: AdminAddData): AxiosPromise => {
  return post("/admins", data);
};

export const adminEdit = (data: Admin): AxiosPromise => {
  return post("/admins/update", data);
};

export function useAdminAdd() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (newData: AdminAddData) => {
      await queryClient.cancelQueries({ queryKey: adminKeys.all() });
      return adminAdd(newData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: adminKeys.all() });
    },
  });
}

export function useAdminDelete() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: AdminDeleteData) => {
      return adminDelete(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: adminKeys.all() });
    },
  });
}

export function useAdminEdit() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: Admin) => {
      return adminEdit(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: adminKeys.all() });
    },
  });
}
